/*
 * @Author: lsjweiyi 759209794@qq.com
 * @Date: 2024-04-02 22:40:50
 * @LastEditors: lsjweiyi 759209794@qq.com
 * @LastEditTime: 2024-04-20 14:50:43
 * @FilePath: \web-ssg\utils\request.ts
 * @Description: 封装的http请求
 */
import { createDiscreteApi } from "naive-ui";
// 指定后端返回的基本数据类型
export interface IResponse<T> {
    logId: string;
    data?: T;
    code: number;
    taskId: string;
    headers: Headers;
    downTimes?: number;
}
// <T, NitroFetchRequest, NitroFetchOptions<NitroFetchRequest, method>>
function fetch<T>(url: string, options?: any, isDown?: boolean): Promise<IResponse<T>> {
    return $fetch<IResponse<T>>(url, {
        ...options,
        baseURL: baseUrlKey().value,
        retry: false,
        onResponse({ response }) {
            let contentType = response.headers.get("content-type");
            let logId = response.headers.get("Log-Id");
            let taskId = response.headers.get("task-id");
            // 请求码不为200等正常码的情况
            if (!response.ok) {
                response._data = { code: -1, data: "请求已到达服务器但未正常响应：" + response.statusText, logId: logId };
                return;
            }

            if (!contentType) {
                response._data = { code: -1, data: "返回数据不符合预期", logId: logId };
                return;
            } else if (contentType == "application/json; charset=utf-8") {
                response._data.logId = logId;
                response._data.taskId = taskId;
                response._data.headers = response.headers;
                return;
            } else {
                const disposition = response.headers.get("content-disposition");
                if (!disposition) {
                    response._data = { code: -1, data: "返回数据不符合预期", logId: logId };
                    return;
                }
                // 切割出文件名
                const fileName = disposition.split("=")[1].replaceAll('"', "");
                const blob = new Blob([response._data], { type: contentType });
                const downUrl = window.URL.createObjectURL(blob);
                // 如果不是为了下载，此处返回该地址即可
                if (!isDown) {
                    response._data = { code: 1, data: downUrl, taskId: taskId, headers: response.headers };
                    return;
                }
                const dom = document.createElement("a");
                dom.href = downUrl;
                dom.download = fileName;
                dom.style.display = "none";
                document.body.appendChild(dom);
                dom.click();
                window.URL.revokeObjectURL(downUrl);
                document.body.removeChild(dom);
                response._data = { code: 1, data: "下载成功!剩余下载次数：" + response.headers.get("down-times"), downTimes: Number(response.headers.get("down-times")) };
                return;
            }
        },
        onRequestError({ error }) {
            console.log(error);

            const { dialog } = createDiscreteApi(["dialog"]);
            dialog.error({
                title: "请求失败！",
                content: "请检查网络是否正常，刷新页面后重试或联系管理员：" + error.message,
                positiveText: "确定",
                onPositiveClick: () => { },
            });
        },
    }).catch((error) => {
        return error.data;
    });
}

export function get<T>(url: string, params?: any, isDown?: boolean) {
    return fetch<T>(url, { method: "get", ...params }, isDown);
}

export function post<T>(url: string, params?: any, isDown?: boolean) {
    return fetch<T>(url, { method: "post", ...params }, isDown);
}
